package com.jiezuo.common.util;

import com.jiezuo.common.exception.BusinessRuntimeException;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @description 封装键值转换工具类
 *             通过键获取值，通过值获取键
 * @author 庞留杰
 * @date 2020/11/9 11:46
 * @version V1.0
 **/
public class ListBuilder {

    private List<InnerBean> innerList;

    public static ListBuilder build() {
        return new ListBuilder();
    }

    public ListBuilder add(String code, String name) {
        if (null == innerList) {
            innerList = new ArrayList<>();
        }
        innerList.add(new InnerBean(code, name));
        return this;
    }

    public List<InnerBean> get() {
        return innerList;
    }

    /**
     * 功能描述: 通过key,获取name
     * @author: 庞留杰
     * @param name
     * @return: code
     * @date: 2020/11/9 11:44
     */
    public String getCodeByName(String name) {
        if(StringUtil.isNotEmpty(name)){
            Optional<InnerBean> t = innerList.stream().filter(bean -> name.trim().equals(bean.getName())).findFirst();
           if(t.isPresent()){//name是否存在
               return t.get().getCode();
           }else {
               throw new BusinessRuntimeException(name+",数据不合法，请检查后重试");
           }
        }else {
            return null;
        }
    }

    /**
     * 功能描述: 通过name,获取key
     * @author: 庞留杰
     * @param code
     * @return: name
     * @date: 2020/11/9 11:45
     */
    public String getNameByCode(String code) {
        if(StringUtil.isNotEmpty(code)){
            Optional<InnerBean> t = innerList.stream().filter(bean -> code.trim().equals(bean.getCode())).findFirst();
            if(t.isPresent()) {//name是否存在
                return t.get().getName();
            }else {
                throw new BusinessRuntimeException(code+",数据不合法，请检查后重试");
            }
        }else {
            return null;
        }
    }

    /**
    * @description   内部类，用于存放键值对
    * @author        庞留杰
    * @date          2020/11/9 14:06
    * @version       V1.0
    **/
    @Data
    class InnerBean {
        private String code;//键
        private String name;//值

        InnerBean(String code, String name) {
            this.code = code;
            this.name = name;
        }
    }

}




